import os

def process_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
    except UnicodeDecodeError:
        # 尝试用gbk编码读取（常见于中文Windows系统）
        try:
            with open(file_path, 'r', encoding='gbk') as f:
                lines = f.readlines()
        except Exception as e:
            print(f"跳过文件 {file_path} (编码错误: {str(e)})")
            return False

    # 检查是否有至少4行且第一行匹配
    if len(lines) < 4:
        return False

    # 检查第一行（去除两端空白和换行符）
    if lines[0].strip() != "by诺艾尔":
        return False

    # 处理前4行：保留第3、4行，然后是第1行（跳过第2行）
    new_lines = [lines[2], lines[3], lines[0]] + lines[4:]

    # 保存修改后的内容（使用原始编码）
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.writelines(new_lines)
    except:
        # 如果utf-8写入失败，尝试用gbk
        with open(file_path, 'w', encoding='gbk') as f:
            f.writelines(new_lines)

    print(f"已处理: {os.path.basename(file_path)}")
    return True

def main():
    current_dir = os.getcwd()
    processed = 0

    for filename in os.listdir(current_dir):
        if filename.lower().endswith('.txt'):
            file_path = os.path.join(current_dir, filename)
            if process_file(file_path):
                processed += 1

    print(f"\n处理完成! 共修改 {processed} 个文件")

if __name__ == "__main__":
    main()